import _ from 'lodash';
import { mapState, mapMutations } from 'vuex';
import {
  getItemsByDictIds,
  getSysTypeIds,
} from '@/api/supplier/components';
export default {
  data () {
    return {
      dictIds: [13, 18, 22, 111, 224, 225, 226, 227, 230, 232, 233, 234, 241, 249, 250, 251, 252, 254, 255, 258, 259, 260, 261, 263, 264, 265, 266, 315, 310, 502, 503],
      sysDictIds: [15, 16, 521, 10040, 10100, 10130, 10131, 10133, 10138, 10146, 10152, 10158, 10159, 10160, 10161, 10162, 10173, 10065],
    }
  },
  computed: {
    ...mapState('supplier/dict', [
      'dictData',
      'sysDictData',
      'dictOptData',
      'sysDictOptData',
    ])
  },
  created () {
    if (!Object.keys(this.dictData).length) {
      getItemsByDictIds(this.dictIds).then(({ result }) => {
        // console.log('getItemsByDictIds', result)
        this.setDictData(result)
        const obj = this.generateDictOptData(result)
        // console.log('obj :>> ', obj);
        this.setDictOptData(obj)
        const diffKeys = _.difference(this.dictIds, Object.keys(result).map(i => parseInt(i)))
        if (diffKeys && diffKeys.length) {
          console.warn(`供应商下列key没有值：${diffKeys.join()}`)
        }
      })
    }

    if (!Object.keys(this.sysDictData).length) {
      getSysTypeIds({ itemIds: this.sysDictIds.join() }).then(({ result }) => {
        // console.log('getSysTypeIds :>> ', result);
        this.setSysDictData(result)
        const obj = this.generateSysDictOptData(result)
        // console.log('obj :>> ', obj);
        this.setSysDictOptData(obj)
        const diffKeys = _.difference(this.sysDictIds, Object.keys(result).map(i => parseInt(i)))
        if (diffKeys && diffKeys.length) {
          console.warn(`系统表下列key没有值：${diffKeys.join()}`)
        }
      })
    }
  },
  methods: {
    ...mapMutations('supplier/dict', [
      'setDictData',
      'setSysDictData',
      'setDictOptData',
      'setSysDictOptData',
    ]),
    // 生成下拉框数据
    generateDictOptData (data) {
      const obj = {}
      for (const [key, value] of Object.entries(data)) {
        const arr = []
        value.forEach(({ enabled, id, itemValue }) => {
          arr.push({
            value: id,
            label: itemValue,
            disable: enabled
          })
        })
        obj[key] = arr
      }
      return obj
    },
    // 生成下拉框数据
    generateSysDictOptData (data) {
      const obj = {}
      for (const [key, value] of Object.entries(data)) {
        const arr = []
        value.forEach(({ sysTypeId, sysTypeName }) => {
          arr.push({
            value: sysTypeId,
            label: sysTypeName
          })
        })
        obj[key] = arr
      }
      return obj
    }
  }
}
